<?php
$loader->requireOnce('ordo/ExaminationType.class.php');
$loader->requireOnce('ordo/Service.class.php');
$loader->requireOnce('includes/ServiceDiscount/ServiceDiscountException.class.php');
$loader->requireOnce('includes/ServiceDiscount/Discountable.class.php');

class DiscountExecuter implements Discountable {

	private $saleProgramId = -1;
		
	/**
	 * 
	 *
	 * @var array['service_id',
	 *            'value',
	 *            'percent]
	 */
	private $saleProgramVal = array();
	
	/**
	 * Constructor
	 *
	 * @param int $examTypeId
	 * @param int $saleProgramId
	 * @throws ServiceDiscountExcepiton if
	 *   $saleProgramId is invalid
	 */
	function __construct($saleProgramId = -1) {
		
		if ($saleProgramId != -1) {			
			$s = Celini::newORDO('SaleProgram', $saleProgramId);
			if (!$s->isExist()) {
				throw new ServiceDiscountException("SaleProgramId <$saleProgramId> does not exist.");
			}
			$this->saleProgramId = $saleProgramId;
			$res = Celini::newORDO('SaleServiceMap')->getServiceBySaleProgram($s->get_id());
			foreach ($res as $item) {
				$temp = array();
				$temp['service_id'] = intval($item['service_id']);
				$temp['value'] = intval($item['value']);
				$temp['percent'] = $item['percent'];
				$this->saleProgramVal[] = $temp;
			}
		}
				
	}	
	/**
	 * Discount on sale program
	 *
	 * @param array $serviceArr
	 *   [service_id => service_price] 
	 *    
	 *   service_price: is the price to discount on
	 */
	public function discountOnSaleProgram($serviceId, $servicePrice) {
		
		$discount = 0;
		if ($this->saleProgramId == -1) {
			return $discount;
		}

		$saleServices = array();		
		foreach ($this->saleProgramVal as $map) {
			$saleServices[] = $map['service_id'];
		}						
		
		// discount		
		if (in_array($serviceId, $saleServices)) {
			$diff = $this->getSaleDiscount($serviceId);			
			$discount = $this->calDiscount($servicePrice, $diff['value'], $diff['percent']);
		}
		
		if ($discount > $servicePrice) {
			$discount = $servicePrice;
		}
		return $discount;
	}
	

	
	private function calDiscount($servicePrice, $value, $percent) {
		if ($percent == 'yes') {
			$dicount = ($servicePrice*$value)/100;
		} else {
			$dicount = $value;
		}
		return $dicount;
	}
	
	private function getSaleDiscount($serviceId) {
		$temp = array('value' => 0,
					  'percent' => 'yes');
		foreach ($this->saleProgramVal as $map) {
			if ($serviceId == $map['service_id']) {
				$temp['value'] = $map['value'];
				$temp['percent'] = $map['percent'];
				break;
			}
		}
		return $temp;		
	}
}
?>